/**
 * Created by studio on 2016/11/18.
 */
// var drag_tab_id = "";//记录当前可拖动页面的表id->放到引用js的页面了
var tab_sort = new Array();//记录序列
var tab_head_id = new Array();//记录表头的列id
var isInit = new Array();//记录已初始化的表id
var drag_col = "";//记录拖动列
var drag_sort_num = -1;//记录拖动中的列的序列
var drop_col = "";//记录拖放列
var tab_head_length = 0;//记录表头列长度
var myurl = "";

//交换两个td
function swapNode(node1,node2)
{
    if(node1 == node2){
        return true;
    }
    if(node1 == undefined || node2 == undefined){
        return false;
    }
    var _parent=node2.parentNode;

    var _t1=node1.nextSibling;
    var _t2=node2.nextSibling;
    if(_t1)
        _parent.insertBefore(node2,_t1);
    else
        _parent.appendChild(node2);
    if(_t2)
        _parent.insertBefore(node1,_t2);
    else
        _parent.appendChild(node1);
}

//初始化序列 实际使用需要传拖动区域的id
function read_tab_head(tab_id){

    if(tab_id == undefined || tab_id == ''){
        return false;
    }

    //读取表头
    // tab_head_length = $('#'+tab_id+' thead tr').find('th').length + $('#'+tab_id+' thead tr').find('td').length;
    tab_head_length = $('#'+tab_id+' thead tr').children().length;
    if(tab_head_length == 0){
        return false;
    }
    for(var i=0;i<tab_head_length;i++){
        if(tab_sort[drag_tab_id].length < tab_head_length){
            tab_sort[drag_tab_id][i] = i;
        }

        if($('#'+tab_id+' thead tr').children().text() != ""){
            tab_head_id[i] = $('#'+tab_id+' thead tr').children().eq(i).attr('id');
        }
    }
    deleteComma(tab_sort[drag_tab_id]);
}

function addEvent(object, event, func) {
    if (object.addEventListener) {
        /* W3C方法（DOM方法）下面语句中的false意思是用于冒泡阶段,若是true则是用于捕获阶段（IE不支持捕获），所以这里用false是一方面的原因是为了统一 */
        object.addEventListener(event, func, false);
        return true;
    } else if (object.attachEvent) { /* MSIE方法(IE方法) */
        object['e' + event + func] = func;
        object[event + func] = function () {
            object['e' + event + func](window.event);
        };
        object.attachEvent('on' + event, object[event + func]);
        return true;
    } /*如两种方法都不具备则返回false */
    return false;
}

//初始化
function dragInit(tab_id){

    if(tab_id == ''){
        return false;
    }

    drag_tab_id = tab_id;

    //判断表是否已经初始化
    for(var i = 0;i < isInit.length;i ++){
        if(isInit[i] == drag_tab_id){
            tab_head_id = [];
            read_tab_head(drag_tab_id);
            return true;
        }
    }
    isInit.unshift(drag_tab_id);

    //初始化数据
    var table = "";
    var onclick = new Array();
    tab_sort[drag_tab_id] = new Array();
    tab_head_id = new Array();
    drag_col = "";
    drag_sort_num = -1;
    drop_col = "";
    tab_head_length = 0;
    myurl = window.location.href.substr(0,window.location.href.indexOf('?'));

    $('#'+drag_tab_id+' thead tr').attr('ondragover','allowDrop(event)');

    table = document.getElementById(tab_id);
    //添加拖拉属性
    if($('#'+drag_tab_id+' thead tr').children().text() != ""){
        $('#'+drag_tab_id+' thead tr').children().attr('draggable','true');
        $('#'+drag_tab_id+' thead tr').children().attr('ondrop','drop(event)');
        $('#'+drag_tab_id+' thead tr').children().attr('ondragover','allowDrop(event)');
        $('#'+drag_tab_id+' thead tr').children().attr('ondragstart','drag(event)');
        $('#'+drag_tab_id+' thead tr').children().attr('ondragend','afterDrag(event)');
        $('#'+drag_tab_id+' thead tr').children().css('outline','none');
        $('#'+drag_tab_id+' thead tr').children().css('overflow','hidden');
        $('#'+drag_tab_id+' thead tr').children().css('text-overflow','ellipsis');
        $('#'+drag_tab_id+' thead tr').children().css('word-break','keep-all');
        $('#'+drag_tab_id+' thead tr').children().css('white-space','nowrap');
    }

    //设置表格的文本超出显示可省略
    $('#'+drag_tab_id).css('table-layout','fixed');
    if($('#'+drag_tab_id).parent().css('overflow') != 'auto'){
        $('#'+drag_tab_id).parent().css('overflow','hidden');
    }

    var op_num = -1;//记录操作那一栏的位置
    for(var l = 0;l < $('#'+drag_tab_id+' thead tr').children().length;l++){
        if($('#'+drag_tab_id+' thead tr').children().eq(l).text() == '操作'){
            op_num = l;
        }
    }
    for(var j = 0;j < $('#'+drag_tab_id+' tbody tr').length;j++){
        $('#'+drag_tab_id+' tbody').find('tr:eq('+j+')').children().css('overflow','hidden');
        $('#'+drag_tab_id+' tbody').find('tr:eq('+j+')').children().css('text-overflow','ellipsis');
        $('#'+drag_tab_id+' tbody').find('tr:eq('+j+')').children().css('word-break','keep-all');
        $('#'+drag_tab_id+' tbody').find('tr:eq('+j+')').children().css('white-space','nowrap');
        if(op_num != -1){//避免'操作'这一栏被td挡住
            $('#'+drag_tab_id+' tbody').find('tr:eq('+j+')').children().eq(op_num).css('word-break','');
            $('#'+drag_tab_id+' tbody').find('tr:eq('+j+')').children().eq(op_num).css('white-space','');
        }
    }

    if($('#'+drag_tab_id+' tbody').text() != null){
        $('#'+drag_tab_id+' tbody').addClass(drag_tab_id+"-sort_body");
    }

    for(j = 0;j < $('#'+drag_tab_id+' thead tr').children().length; j++) {
        var child = $('#' + drag_tab_id + ' thead tr').children().eq(j);
        onclick[j] = child.attr('onclick');
        if (child.attr('id') == "" || child.attr('id') == undefined) {//添加id 以内容为id
            child.attr('id',drag_tab_id + '_child' + j);
        }
    }

    var focus = -1;
    var mouseDown = false;
    //列宽调整
    //找了网上的addEvent方法来实现全局捕捉，来源忘记了.. 下面 右边的条件去掉 明细拖动开启
    if(table != ""){
        //明细列宽调整暂不开放
        addEvent(document,"mousedown",function(e){
            e = e || window.event;
            if(table.id != drag_tab_id || $.inArray(e.target.id,tab_head_id) == -1){
                return false;
            }

            for(k = 0;k < table.rows[0].cells.length;k++){

                //限定点击区域的y坐标
                if(event.y < table.getBoundingClientRect().top || event.y >= (table.rows.length > 1? table.rows[1].getBoundingClientRect().top:table.getBoundingClientRect().bottom)){
                    return false;
                }

                //每个单元格的横向划分 k代表第几个位置 从0开始
                if(k != table.rows[0].cells.length-1 && event.x > table.rows[0].cells[k].getBoundingClientRect().left && event.x <= table.rows[0].cells[k].getBoundingClientRect().right){
                    if (event.offsetX > table.rows[0].cells[k].offsetWidth - 10){
                        //创建div,标识线（虚线）
                        if(!document.getElementById('split'+k)){
                            var div = document.createElement('div');
                            div.id = 'split'+k;
                            table.appendChild(div);
                        }

                        div = document.getElementById('split'+k);
                        div.style.cssText = "height:" + table.clientHeight + "px;top:" + table.getBoundingClientRect().top + "px;left:" + event.x + "px;width:1px;position:fixed;background-color:#7EC0EE";

                        focus = k;
                        mouseDown = true;

                        //拖拉、排序禁用
                        for(var k = 0;k < $('#'+drag_tab_id+' thead tr').children().length;k ++){
                            $('#'+drag_tab_id+' thead tr').children().eq(k).attr('onclick',false);
                        }
                        $('#'+drag_tab_id+' thead tr').children().attr('draggable','false');
                        document.onselectstart = function(){return false;}
                    }
                }
            }
        });

        addEvent(document,"mousemove",function(e){
            e = e || window.event;
            if(table.id != drag_tab_id){
                return false;
            }

            //更改鼠标样式（点击前）
            for(var k = 0;k < table.rows[0].cells.length && mouseDown == false;k++){
                if (event.offsetX > table.rows[0].cells[k].offsetWidth - 10 && k != table.rows[0].cells.length - 1){
                    table.rows[0].cells[k].style.cursor = 'col-resize';
                }
                else{
                    table.rows[0].cells[k].style.cursor = 'pointer';
                }
            }
            if(focus != -1 && document.getElementById('split'+focus) != undefined && event.x >= table.getBoundingClientRect().left && (table.parentElement.className == "col-sm-12"?event.x<= table.getBoundingClientRect().right:event.x <= table.parentElement.getBoundingClientRect().right)){

                if (mouseDown != null && mouseDown == true) {
                    //虚线移动
                    var div = document.getElementById('split'+focus);
                    div.style.cssText = "height:" + table.clientHeight + "px;top:"+ table.getBoundingClientRect().top +"px;left:" + event.x + "px;width:1px;position:fixed;background-color:#7EC0EE";

                    document.body.style.cursor = 'col-resize';
                }
            }

        });

        addEvent(document,"mouseup",function(e){
            e = e || window.event;
            if(table.id != drag_tab_id){
                return false;
            }

            if(focus != -1 && document.getElementById('split'+focus) != undefined){
                document.getElementById('split'+focus).remove();

                // $('#'+drag_tab_id+' thead tr').find('th').attr('draggable','true');
                // $('#'+drag_tab_id+' thead tr').find('td').attr('draggable','true');

                //结束宽度调整，拖拉、排序启用
                $('#'+drag_tab_id+' thead tr').children().attr('draggable','true');
                for(var k = 0;k < $('#'+drag_tab_id+' thead tr').children().length;k ++){
                    $('#'+drag_tab_id+' thead tr').children().eq(k).attr('onclick',onclick[k]);
                }

                var left = $('#'+drag_tab_id+' thead tr').children().eq(focus);
                var right = $('#'+drag_tab_id+' thead tr').children().eq(focus+1);
                //计算宽度：左
                var left_border_left = left.css('border-left-width').substr(0,left.css('border-left-width').indexOf("px"));
                var left_border_right = left.css('border-right-width').substr(0,left.css('border-right-width').indexOf("px"));
                var left_padding_right = left.css('padding-right').substr(0,left.css('padding-right').indexOf("px"));
                var left_padding_left = left.css('padding-left').substr(0,left.css('padding-left').indexOf("px"));
                var left_width = event.x - document.getElementById(left.attr('id')).getBoundingClientRect().left - left_padding_right - left_padding_left - left_border_left - left_border_right;

                //计算宽度：右
                var right_border_left = right.css('border-left-width').substr(0,right.css('border-left-width').indexOf("px"));
                var right_border_right = right.css('border-right-width').substr(0,right.css('border-right-width').indexOf("px"));
                var right_padding_right = right.css('padding-right').substr(0,right.css('padding-right').indexOf("px"));
                var right_padding_left = right.css('padding-left').substr(0,right.css('padding-left').indexOf("px"));
                var right_width = document.getElementById(right.attr('id')).getBoundingClientRect().right - right_padding_right - right_padding_left - event.x - right_border_left - right_border_right;

                //设定宽度
                if(left_width > 0 && right_width > 0
                    && event.x < document.getElementById(right.attr('id')).getBoundingClientRect().right
                    && event.x > document.getElementById(left.attr('id')).getBoundingClientRect().left){
                    left.attr('width',left_width);
                    right.attr('width',right_width);
                    for(k = 0;k < $('#'+drag_tab_id+' thead tr').children().length;k ++){
                        var head = $('#'+drag_tab_id+' thead tr').children().eq(k);
                        head.attr('width',(document.getElementById(head.attr('id')).getBoundingClientRect().width/table.getBoundingClientRect().width)*100+"%");
                    }
                }

                mouseDown = false;
                focus = -1;
                document.body.style.cursor = 'default';
                document.onselectstart = function(){return true;};

                //列宽发生调整,弹出提示框是否保存
                tableSequence(drag_tab_id);
            }
        });
    }

    //读取table顺序
    getTableSequence(drag_tab_id);
}

//排序
function sort(tab_id){
    var tb_length = $('#'+tab_id+' tbody tr').length;
    var init_tab_head_id = new Array();

    if(tb_length > 0){
        var d = document.getElementsByClassName(tab_id+'-sort_body');
    }

    for(var i=0;i<tab_sort[tab_id].length;i++){
        init_tab_head_id[i] = tab_head_id[tab_sort[tab_id][i]];
    }

    for(var i=0;i<tab_head_id.length;i++){
        var change_num = -1;
        //表头排序
        swapNode(document.getElementById(tab_head_id[i]),document.getElementById(init_tab_head_id[i]));

        for(var k=0;k<tab_head_id.length;k++){
            if(init_tab_head_id[i] == tab_head_id[k]){
                change_num = k;
                break;
            }
        }
        // 表体排序
        for(var j = 0;j < tb_length; j++){
            var node1 = d[0].children.item(j).cells[i];
            var node2 = d[0].children.item(j).cells[change_num];
            swapNode(node1,node2);
        }
        read_tab_head(tab_id);
    }
}

//pjax加载后进行表格的重新初始化
// $(document).on('pjax:complete', function() {
//     // pjax完成后 拖拉相关
//     try{
//         dragInit_after_pjax(drag_tab_id);
//     }catch (e){
//         return false;
//     }
// });

function dragInit_after_pjax(tab_id){
    for(var i = 0;i < isInit.length;i ++){
        if(isInit[i] == tab_id){
            isInit[i] = "";
        }
    }
    dragInit(tab_id);
}

//表头还原
function head_back(tab_id){
    read_tab_head(tab_id);

    var init_tab_head_id = new Array();
    for(var i=0;i<tab_sort[tab_id].length;i++){
        init_tab_head_id[tab_sort[tab_id][i]] = tab_head_id[i];
    }

    for(var i=0;i<tab_head_id.length;i++){
        swapNode(document.getElementById(tab_head_id[i]),document.getElementById(init_tab_head_id[i]));
        read_tab_head(tab_id);
    }

    // 重新读取cookie记录到tab_sort
    if($.cookie(myurl+tab_id+'sort') != null){
        for(var i=0;i<$.cookie(myurl+tab_id+'sort').split(',').length;i++){
            var j = i;
            tab_sort[tab_id][i] = $.cookie(myurl+tab_id+'sort').split(',')[j];
        }
    }
}

//单行排序
function sort_one_row(tr){
    var init_sort_row = new Array();

    for(var i = 0;i < tr.find('td').length; i++){
        init_sort_row[i] = tr.find('td')[tab_sort[drag_tab_id][i]];
    }

    for(var i=0;i<tab_head_id.length;i++){
        swapNode(tr.find('td')[i],init_sort_row[i]);
    }
}


/**
 * 拖动区域列表初始化
 * @param key table_id
 */
function drag_tab_change(key){
    $("#mylayer").parent().remove();
    dragInit(key);
}

function drag(ev) {
    for(var i=0;i<tab_head_length;i++){
        if(tab_head_id[i] == ev.target.id){
            drag_col = i;
            drag_sort_num = tab_sort[drag_tab_id][i];
        }
    }
}

function drop(ev)
{
    ev.preventDefault();
    if(drag_col == undefined || drag_col == '' && drag_col != '0'){
        return false;
    }

    var tb_length = $('#'+drag_tab_id+' tbody tr').length;
    if(tb_length > 0){
        var d = document.getElementsByClassName(drag_tab_id+'-sort_body');
    }

    for(var i=0;i<tab_head_length;i++){
        if(tab_head_id[i] == ev.target.id){
            drop_col = i;
        }
    }

    if(drag_col < drop_col){
        for(var i=drag_col;i<drop_col;i++){
            swapNode(document.getElementById(tab_head_id[drag_col]),document.getElementById(tab_head_id[i+1]));
            for(var j = 0;j < tb_length; j++){
                var node1 = d[0].children.item(j).cells[i];
                var node2 = d[0].children.item(j).cells[i+1];
                swapNode(node1,node2);
            }
            tab_sort[drag_tab_id][i] = tab_sort[drag_tab_id][i+1];
        }
    }else if(drag_col > drop_col){
        for(var i=drag_col;i>drop_col;i--){
            swapNode(document.getElementById(tab_head_id[drag_col]),document.getElementById(tab_head_id[i-1]));
            for(var j = 0;j < tb_length; j++){
                var node1 = d[0].children.item(j).cells[i];
                var node2 = d[0].children.item(j).cells[i-1];
                swapNode(node1,node2);
            }
            tab_sort[drag_tab_id][i] = tab_sort[drag_tab_id][i-1];
        }
    }

    if(drag_col != drop_col){
        tab_sort[drag_tab_id][i] = drag_sort_num;
    }

    read_tab_head(drag_tab_id);//以当前表头顺序读取id存入数组
    //列序发生调整,弹出提示框是否保存
    if(drop_col != drag_col)
        tableSequence(drag_tab_id);

    drag_col = '';
}

function allowDrop(ev)
{
    //移动到允许拖放区域时触发
    ev.preventDefault();
    if(drag_col == undefined || drag_col == '' && drag_col != '0'){
        return false;
    }
    for(var i = 0;i < tab_head_id.length;i ++){//拖拉处颜色变化
        if(!document.getElementById('sort_div')){
            var div = document.createElement('div');
            div.id = 'sort_div';
            document.getElementById(drag_tab_id).appendChild(div);
        }
        div = document.getElementById('sort_div');

        if(ev.target.id != tab_head_id[i]){
            $('#'+tab_head_id[i]).css('backgroundColor','#FFF');
        }else{
            if(ev.target.id != tab_head_id[drag_col]){
                ev.target.style.backgroundColor = '#D1EEEE';
                if(drag_col > i)
                    div.style.cssText = "height:" + document.getElementById(drag_tab_id).clientHeight + "px;top:" + document.getElementById(drag_tab_id).getBoundingClientRect().top + "px;left:" + document.getElementById(tab_head_id[i]).getBoundingClientRect().left + "px;width:2px;position:fixed;background-color:#00CDCD";
                else if(drag_col < i)
                    div.style.cssText = "height:" + document.getElementById(drag_tab_id).clientHeight + "px;top:" + document.getElementById(drag_tab_id).getBoundingClientRect().top + "px;left:" + document.getElementById(tab_head_id[i]).getBoundingClientRect().right + "px;width:2px;position:fixed;background-color:#00CDCD";
            }else{
                document.getElementById('sort_div').remove();
            }
        }
    }
}

function afterDrag(ev)
{
    ev.preventDefault();
    for(var i = 0;i < tab_head_id.length;i ++){//颜色回到默认的白色
        $('#'+tab_head_id[i]).css('backgroundColor','#FFF');
    }
    if(document.getElementById('sort_div') != null){
        document.getElementById('sort_div').remove();
    }
}


function getTableSequence(drag_tab_id) {
    //获取路由
    //如http://wyf.io/jxc2.0/backend/web/index.php?r=order%2Findex
    //取得order
    var route = window.location.href.substring(window.location.href.indexOf('?r=')+3);
    route = route.substr(0,route.indexOf('%'));
    if($.cookie(route+drag_tab_id+"width") == null || $.cookie(route+drag_tab_id) == null){
        //读
        $.ajax({
            type: "GET",
            url:  window.location.pathname+"?r="+route +"%2Foperate-sequence",
            data: {"table_route":(route+drag_tab_id),"sequence":"","width":""},
            cache: false,
            dataType:"json",
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                alertFailed("读取列失败");
            },
            success: function(data){
                if(data.code != 0) {

                    data.sequence = data.sequence.split(',');
                    data.width = data.width.split(',');
                }
                var expireDate = new Date();
                expireDate.setTime((expireDate.getTime() + (1 * 60 * 60000)));
                $.cookie(route+drag_tab_id,data.sequence,{ expires:expireDate });
                $.cookie(route+drag_tab_id+"width",data.width,{ expires:expireDate });

                for(var i = 0 ; i < data.sequence.length ; i++){
                    tab_sort[drag_tab_id][i] = data.sequence[i];
                }

                var table = document.getElementById(drag_tab_id);

                for(var i = 0 ; i < table.rows[0].cells.length ; i++){
                    if(data.width[i]!='' && data.width[i]!=undefined)
                    {
                        for(var j = 0 ; j < table.rows.length ; j++){
                            table.rows[j].cells[i].width = data.width[i];
                        }
                    }
                }

                if(read_tab_head(drag_tab_id) != false){
                    sort(drag_tab_id);
                }
            }
        });
    }
    else{

        var sequence = $.cookie(route+drag_tab_id).split(',');
        for(var i=0;i<sequence.length;i++){
            var j = i;
            tab_sort[drag_tab_id][i] = sequence[j];
        }
        if(read_tab_head(drag_tab_id) != false){
            sort(drag_tab_id);
        }

        var width = $.cookie(route+drag_tab_id+"width").split(',');
        var table = document.getElementById(drag_tab_id);
        for(var i = 0 ; i < table.rows[0].cells.length ; i++){
            if(width[i]!='' && width[i]!=undefined)
            {
                for(var j = 0 ; j < table.rows.length ; j++){
                    table.rows[j].cells[i].width = width[i];
                }
            }
        }

    }
}

function tableSequence(drag_tab_id){
    layer.msg('同步列表调整到服务器？', {
        btn: ['保存','取消'],
        time: 15000,
        id:'mylayer',
        offset:['30px','60%'],
        btn1:function(){
            //获取路由
            //如http://wyf.io/jxc2.0/backend/web/index.php?r=order%2Findex
            //取得order
            var route = window.location.href.substring(window.location.href.indexOf('?r=')+3);
            route = route.substr(0,route.indexOf('%'));
            var table = document.getElementById(drag_tab_id);
            var width = new Array();
            for(var i = 0 ; i < table.rows[0].cells.length ; i++){
                width[i] = table.rows[0].cells[i].width==null?'':parseFloat(table.rows[0].cells[i].width).toFixed(2)+'%';
            }
            //设置cookie1小时
            var expireDate= new Date();
            expireDate.setTime((expireDate.getTime() + (1 * 60 * 60000)));
            $.cookie(route+drag_tab_id,tab_sort[drag_tab_id].join(","),{ expires:expireDate });
            $.cookie(route+drag_tab_id+"width",width,{ expires:expireDate });
            //存储
            $.ajax({
                type: "GET",
                url:  window.location.pathname+"?r="+route +"%2Foperate-sequence",
                data: {"table_route":(route+drag_tab_id),'sequence':tab_sort[drag_tab_id].join(","),"width":width.join(",")},
                cache: false,
                dataType:"json",
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    alertFailed("保存失败");
                },
                success: function(){
                    layer.msg('保存成功',{time:600});
                }
            });
        },btn2: function(){
            layer.msg('暂不保存',{time:600});
        }});
}

function deleteComma(arr){
    for(var i = 0 ; i < arr.length ; i++){
        if(arr[i] == ','){
            arr.splice(i,1);
        }
    }
}

//从初始化列表中删除某张表 后来加的- -
function isInitDelete(tab_id){
    for(var i = 0;i < isInit.length;i ++){
        if(isInit[i] == tab_id){
            //表头还原
            head_back(tab_id);
        }
    }
}